package tiny.soft.com.common.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @ClassName SpringBeanUtils
 * @Description
 * @Author 张祖昌
 * @Date 2019/4/22 9:35
 * @Version 1.0
 **/
@Component
public class SpringBeanUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (SpringBeanUtils.applicationContext == null) {
            SpringBeanUtils.applicationContext = applicationContext;
        }
    }

    /**
      *获取applicationContext
      * @Author 张祖昌
      * @Description
      * @Date 2019/4/22 9:36
      * @param
      * @return org.springframework.context.ApplicationContext
      **/
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
      * 通过name获取 Bean.
      * @Author 张祖昌
      * @Description
      * @Date 2019/4/22 9:37
      * @param name
      * @return java.lang.Object
      **/
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);

    }

    /**
      *通过class获取Bean.
      * @Author 张祖昌
      * @Description
      * @Date 2019/4/22 9:37
      * @param clazz
      * @return T
      **/
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
      *通过name,以及Clazz返回指定的Bean
      * @Author 张祖昌
      * @Description
      * @Date 2019/4/22 9:37
      * @param name
      * @param clazz
      * @return T
      **/
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}